#include "Con_mqtt.h"
#include "esp_log.h"

// 添加TAG定义
static const char *TAG = "MQTT";

#define CONFIG_BROKER_URL "mqtt://broker.emqx.io:1883/mqtt"

static esp_mqtt_client_handle_t client = NULL;

// 函数声明
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data);
static int mqtt_send_data(const char *topic, const char *data, int qos, int retain);
static int mqtt_send_motor_status(int id, const char* connectType, int motorStatus, int speed);

void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = CONFIG_BROKER_URL,
    };

    // 初始化客户端
    client = esp_mqtt_client_init(&mqtt_cfg);
    if (client == NULL) {
        ESP_LOGE(TAG, "MQTT客户端初始化失败");
        return;
    }

    // 注册mqtt事件处理函数
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    // 启动mqtt客户端
    esp_mqtt_client_start(client);

    ESP_LOGI(TAG, "MQTT客户端启动成功");
}

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    esp_mqtt_event_handle_t event = event_data;

    switch((esp_mqtt_event_id_t)event_id)
    {
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
            break;
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
            break;
        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_UNSUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_PUBLISHED:
            ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_DATA:
            // 因为我们不需要接收，所以这里什么都不做
            // 注释掉原来的数据处理函数调用
            break;
        case MQTT_EVENT_ERROR:
            ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
            break;
        default:
            ESP_LOGI(TAG, "Other event id:%d", event->event_id);
            break;
    }
}

// 发送数据的函数
static int mqtt_send_data(const char *topic, const char *data, int qos, int retain)
{
    if (client == NULL) {
        ESP_LOGE(TAG, "MQTT客户端未初始化");
        return -1;
    }
    
    int msg_id = esp_mqtt_client_publish(client, topic, data, 0, qos, retain);
    ESP_LOGI(TAG, "发送消息到主题 %s: %s, msg_id=%d", topic, data, msg_id);
    return msg_id;
}

// 发送特定格式数据的专用函数
static int mqtt_send_motor_status(int id, const char* connectType, int motorStatus, int speed)
{
    char json_data[128];
    snprintf(json_data, sizeof(json_data), 
             "{\"id\":%d,\"connectType\":\"%s\",\"motorStatus\":%d,\"speed\":%d}",
             id, connectType, motorStatus, speed);
    
    return mqtt_send_data("lijaifeng", json_data, 0, 0);
}

// 发送示例数据的函数（供外部调用）
void send_example_data(void)
{
    // 发送您指定的格式
    mqtt_send_motor_status(5, "lora", 1, 127);
}